package com.jamal2362.apktool.view;

import android.view.View;
import android.widget.ImageView;
import java.util.LinkedList;
import java.util.List;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.util.IconFactory;
import com.jamal2362.apktool.util.IconTypes;
import com.jamal2362.apktool.util.Settings;
import android.content.Context;

public class TreeNode<T>
{
	private T t;
	private final int depth;
	private final List<TreeNode<T>> childs;
	private int count = 0;
	private boolean isExpand;
	private TreeListAdapter content;
	
	public TreeNode(int depth, TreeListAdapter content)
	{
		this(null, depth, content);
	}
	
	public TreeNode(T t, int depth, TreeListAdapter content)
	{
		this.t = t;
		this.content = content;
		this.depth = depth;
		isExpand = false;
		childs = new LinkedList<>();
	}

	public T getT()
	{
		return t;
	}

	public int getDepth()
	{
		return depth;
	}

	public void onClick(TreeAdapter<T> adapter, View view)
	{
		if (count == 0 || !adapter.shouldShowExpandDrawable())
		{
			adapter.onClick(t, view);
			return;
		}
		isExpand = !isExpand;
		content.refresh();
	}

	public void setState(ImageView state, TreeAdapter<T> adapter, int p1)
	{
		if (adapter.shouldShowExpandDrawable())
		{
			Context ctx = state.getContext();
			IconFactory icf = new IconFactory(ctx);
			icf.round(Settings.roundIcons);
			int icBg = (p1 % 2) == 0 ? IconTypes.colorApk : IconTypes.colorVideo;
			if (childs.size() == 0)
				state.setImageDrawable(null);
			else
				state.setImageBitmap(icf.makeIcon(icBg, R.drawable.ic_apk));
		}
	}

	public void addChilds(List<TreeNode<T>> allNodes, TreeAdapter<T> adapter)
	{
		if (isExpand || !adapter.shouldShowExpandDrawable() || depth < 0)
		{
			List<TreeNode<T>> childs = this.childs;
			for (int i = 0; i < count; i++)
			{
				TreeNode<T> node = childs.get(i);
				allNodes.add(node);
				node.addChilds(allNodes, adapter);
			}
		}
	}

	public void initWithTreeAdapter(T t, TreeAdapter<T> adapter)
	{
		this.t = t;
		int count = adapter.getChildCount(t);
		for (int i=0;i < count;i++)
			get(i).initWithTreeAdapter(adapter.getChild(t, i), adapter);
		this.count = count;
	}

	private TreeNode<T> get(int idx)
	{
		TreeNode<T> node;
		if (idx >= childs.size())
		{
			node = new TreeNode<T>(depth + 1, content);
			childs.add(node);
		}
		else
		{
			node = childs.get(idx);
		}
		return node;
	}
}
